from flask import Blueprint, request, render_template, flash, redirect, url_for,session,g
from flask_mail import Message
from exts import mail, db,cache
from forms import userform
import random
from werkzeug.security import generate_password_hash,check_password_hash
from models.user import UserModel

bp = Blueprint("user",__name__,url_prefix="/user")


@bp.route("/register",methods=["GET",'POST'])
def register():
    if request.method == 'GET':
        return render_template("front/register.html")
    else:
        form = userform.registerForm(request.form)
        if form.validate():
            username = form.username.data
            password = form.password.data
            email = form.email.data
            user = UserModel(username=username,password=generate_password_hash(password),email=email)
            db.session.add(user)
            db.session.commit()
            return redirect(url_for("user.login"))
        else:
            for error in form.errors.values():
                for message in error:
                    flash(message)
            return redirect(url_for("user.register"))


@bp.route('/captcha')
def mail_captcha():
    email = request.args.get("email")
    num = ['1','2','3','4','5','6','7','8','9']
    captcha = "".join(random.sample(num,4))
    message = Message(subject='图书馆验证码',recipients=[email],body=f"您的验证码:{captcha}")
    mail.send(message)
    cache.set(email,captcha,timeout=300)
    return {'status':200,"captcha":captcha}


@bp.route("/login",methods=['GET','POST'])
def login():
    if request.method == "GET":
        return render_template("front/login.html")
    else:
        form = userform.loginForm(request.form)
        if form.validate():
            email = form.email.data
            password = form.password.data
            user = UserModel.query.filter_by(email=email).first()
            if not user:
                flash("该邮箱不存在")
                return redirect(url_for("user.login"))
            if not user.is_active:
                flash("该账号被冻结")
                return redirect(url_for("user.login"))
            if check_password_hash(user.password, password):
                session['user_id'] = user.id
                return redirect('/')
            else:
                flash("密码错误")
                return redirect(url_for("user.login"))
        else:
            for errors in form.errors.values():
                for error in errors:
                    flash(error)
            return redirect(url_for("user.login"))


@bp.route("/logout")
def logout():
    session.clear()
    return redirect("/")
